from dataclasses import dataclass, field
from typing import Dict, List
from .type_system import LanguageTypeMapper
from .field_processor import FieldProcessor
from .sql_table_info import ColumnInfoSQL, TableInfoSQL, TableInfoConfig, ColumnConfig

@dataclass
class MetaInfoProcessor:
    """元数据处理的核心类"""
    type_mapper: LanguageTypeMapper
    field_processor: FieldProcessor

    def process_column(self, column_sql: ColumnInfoSQL, config: ColumnConfig, target_language: str) -> dict:
        """处理单个列的元数据"""
        base_type = self.type_mapper.get_type(column_sql.type, target_language)
        field_name = (
            self.field_processor.to_camel_case(column_sql.name)
            if target_language == 'typescript'
            else column_sql.name
        )

        return {
            'name': column_sql.name,
            'field_name': field_name,
            'language_type': f"{base_type} | null" if config.nullable and target_language == 'typescript' else base_type,
            'is_primary': column_sql.primary_key,
            'is_nullable': config.nullable,
            'chinese_name': config.chinese_name,
            'editable': config.editable and not column_sql.auto_increment,
            'searchable': config.column_show,
            'listable': config.column_show,
            'field_type': config.field_type,
            'value_map': config.value_map,
            'comment': config.comment,
            'mock_rule': config.mock_rule,
        }

@dataclass
class MetaInfoContainer:
    """元数据容器"""
    sql_info: TableInfoSQL
    config: TableInfoConfig
    processor: MetaInfoProcessor
    columns_meta: List[dict] = field(default_factory=list)

    def __post_init__(self):
        self.process_columns()

    def process_columns(self):
        """处理所有列的元数据"""
        self.columns_meta = [
            self.processor.process_column(col, col_config, self.config.target_language)
            for col, col_config in zip(self.sql_info.columns, self.config.columns)
        ]

    @property
    def primary_keys(self) -> List[dict]:
        """获取主键信息"""
        return [
            {
                'name': self.processor.field_processor.to_camel_case(col['name']),
                'type': col['language_type']
            }
            for col in self.columns_meta if col['is_primary']
        ]